package com.songcha.library_common.ui.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint.FontMetrics
import android.util.AttributeSet
import android.widget.TextView
import com.songcha.library_common.util.FontUtil
import kotlin.math.absoluteValue
import kotlin.math.ceil

/***
 * exclude padding of textview
 * attention:cause font is different in every phone,so fontMetrics is also different
 */
@SuppressLint("AppCompatCustomView")
class NoPaddingTextView @JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0,
    defRes: Int = 0
) :TextView(context,attrs,defStyle,defRes) {

    init {
        initView(context,attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?){
        //force set includeFontPadding,otherwise text will be clipped
        includeFontPadding = true
        setTextPadding()
    }

    override fun setText(text: CharSequence?, type: BufferType?) {
        super.setText(text, type)
        setTextPadding()
    }

    override fun setTextSize(size: Float) {
        super.setTextSize(size)
        setTextPadding()
    }


    private fun setTextPadding(){
        val isBold=typeface.isBold or paint.isFakeBoldText
        val bounds=FontUtil.getTextBounds(text.toString(),null,textSize,isBold)?:return
        val standardBounds=FontUtil.getTextBounds("f",null,textSize,isBold)?:return
        //fm is fix,not relative to text content
        val fm=FontUtil.getFontMetrics(null,textSize,isBold)?:return
        //fm is real height,bounds is min hegiht,textsize is not usefully
        //a has top,bottom;b has top,nobottom;g has bottom,no top,Q has top,bottom;
        //final effect is center base on f(-x,0),other will be clipped
        var delta=(fm.bottom-fm.top)-(standardBounds.height())

        if(delta>0){
            //prevent being clipped
            val p=(ceil(-delta/2.0)).toInt()
            val diffTop=standardBounds.top-bounds.top
            val diffBottom=standardBounds.bottom-bounds.bottom
            setPadding(0,p+diffTop,0,p-diffBottom)
        }

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
    }


}